package cn.zebra.dev.mall.module.product.controller;

import cn.zebra.dev.common.constant.ParamsConstant;
import cn.zebra.dev.common.restful.Result;
import cn.zebra.dev.common.utils.ObjectUtils;
import cn.zebra.dev.ibatis.plus.utils.PageUtils;
import cn.zebra.dev.mall.module.product.dto.ProductQuestionListDTO;
import cn.zebra.dev.mall.module.product.dto.ProductQuestionReplyListDTO;
import cn.zebra.dev.mall.module.product.vo.ProductQuestionQueryVO;
import cn.zebra.dev.mall.module.product.vo.ProductQuestionReplyVO;
import cn.zebra.dev.mall.module.product.vo.ProductQuestionVO;
import cn.zebra.dev.member.module.login.service.SecurityMemberService;
import cn.zebra.dev.product.module.product.entity.ProductEntity;
import cn.zebra.dev.product.module.product.service.ProductService;
import cn.zebra.dev.product.module.question.entity.ProductQuestionEntity;
import cn.zebra.dev.product.module.question.entity.ProductQuestionReplyEntity;
import cn.zebra.dev.product.module.question.service.ProductQuestionReplyService;
import cn.zebra.dev.product.module.question.service.ProductQuestionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "商品问题")
@RestController
@RequestMapping("/product/question/")
public class ProductQuestionController {
    @Autowired
    private ProductQuestionService productQuestionService;

    @Autowired
    private ProductQuestionReplyService productQuestionReplyService;

    @Autowired
    private SecurityMemberService securityMemberService;

    @Autowired
    private ProductService productService;

    @GetMapping("/list")
    @ApiOperation("获取商品问题列表")
    public Result<PageUtils<ProductQuestionListDTO>> list(
            ProductQuestionQueryVO vo,
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page) {
        Map<String, Object> map = ObjectUtils.objectConvertMap(vo);
        map.put("limit", limit);
        map.put("page", page);
        PageUtils<ProductQuestionEntity> pageUtils = productQuestionService.findPage(map);
        List<ProductQuestionEntity> list = pageUtils.getList();
        List<ProductQuestionListDTO> dtoList = new ArrayList<>();
        if (list.size() > 0 ){
            List<Long> ids = list.stream().map(ProductQuestionEntity::getId).collect(Collectors.toList());
            List<ProductQuestionReplyEntity> questionReplyEntities = productQuestionReplyService.findByIds(ids);
            list.forEach(entity -> {
                ProductQuestionListDTO productQuestionListDTO = new ProductQuestionListDTO();
                List<ProductQuestionReplyEntity> replyEntityList = questionReplyEntities.stream().filter(productQuestionReplyEntity -> productQuestionReplyEntity.getProductQuestionId().equals(entity.getId())).collect(Collectors.toList());
                entity.setQuestionReplyContentList(replyEntityList);
                entity.setReplyCount(replyEntityList.size());
                BeanUtils.copyProperties(entity, productQuestionListDTO);
                dtoList.add(productQuestionListDTO);
            });
        }
        PageUtils<ProductQuestionListDTO> data = new PageUtils<>(pageUtils);
        data.setList(dtoList);
        return Result.success(data);
    }

    @PostMapping("/save")
    @ApiOperation("保存商品问题")
    public Result save(@Valid @RequestBody ProductQuestionVO vo) {
        if (productService.getById(vo.getProductId()) == null) {
            return Result.error("该商品不存在!");
        }
        ProductQuestionEntity entity = new ProductQuestionEntity();
        BeanUtils.copyProperties(vo, entity);
        Long memberId = securityMemberService.getMemberId();
        String memberHeadImg = securityMemberService.getMemberPhoto();
        String memberName = securityMemberService.getMemberName();
        entity.setMemberId(memberId);
        entity.setMemberName(memberName);
        entity.setMemberHeadImg(memberHeadImg);
        entity.setQuestionContent(vo.getQuestionContent());
        entity.setProductId(vo.getProductId());
        ProductEntity productEntity = productService.findById(vo.getProductId());
        entity.setProductName(productEntity.getProductName());
        entity.setCreateTime(LocalDateTime.now());
        if (productQuestionService.save(entity)) {
            return Result.success("添加成功！");
        }
        return Result.error("保存失败!");
    }

    @GetMapping("/delete/{id}")
    @ApiOperation("删除商品问题")
    public Result delete(@PathVariable Long id) {
        ProductQuestionEntity entity = new ProductQuestionEntity();
        entity.setDeleteFlag(true);
        if (productQuestionService.update(entity, "id = {0}", id)) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败!");
    }

    @GetMapping("/listQuestionReply")
    @ApiOperation("获取商品问题回复列表")
    public Result<PageUtils<ProductQuestionReplyListDTO>> listQuestionReply(
            Long productQuestionId,
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page) {
        Map<String, Object> params = new HashMap<>();
        params.put(ParamsConstant.PAGE, page);
        params.put("product_question_id", productQuestionId);
        params.put(ParamsConstant.LIMIT, limit);
        PageUtils<ProductQuestionReplyEntity> pageUtils = productQuestionReplyService.findPage(params);
        List<ProductQuestionReplyEntity> list = pageUtils.getList();
        List<ProductQuestionReplyListDTO> dtoList = new ArrayList<>();
        list.forEach(entity -> {
            ProductQuestionReplyListDTO productQuestionReplyListDTO = new ProductQuestionReplyListDTO();
            BeanUtils.copyProperties(entity, productQuestionReplyListDTO);
            dtoList.add(productQuestionReplyListDTO);
        });
        PageUtils<ProductQuestionReplyListDTO> data = new PageUtils<>(pageUtils);
        data.setList(dtoList);
        return Result.success(data);
    }

    @PostMapping("/saveQuestionReply")
    @ApiOperation("保存商品问题回复")
    public Result saveQuestionReply(@Valid @RequestBody ProductQuestionReplyVO vo) {
        if (productQuestionService.findById(vo.getProductQuestionId()) == null){
            return Result.error("该商品没有问题");
        }
        ProductQuestionReplyEntity entity = new ProductQuestionReplyEntity();
        BeanUtils.copyProperties(vo, entity);
        Long memberId = securityMemberService.getMemberId();
        String memberHeadImg = securityMemberService.getMemberPhoto();
        String memberName = securityMemberService.getMemberName();
        entity.setMemberReplyId(memberId);
        entity.setMemberReplyName(memberName);
        entity.setMemberReplyHeadImg(memberHeadImg);
        entity.setProductQuestionReplyContent(vo.getProductQuestionReplyContent());
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        if (productQuestionReplyService.save(entity)) {
            return Result.success("添加成功！");
        }
        return Result.error("保存失败!");
    }

    @GetMapping("/deleteQuestionReply/{id}")
    @ApiOperation("删除商品问题回复")
    public Result deleteQuestionReply(@PathVariable Long id) {
        ProductQuestionReplyEntity questionReplyEntity = new ProductQuestionReplyEntity();
        questionReplyEntity.setDeleteFlag(true);
        if (productQuestionReplyService.update(questionReplyEntity, "id = {0}", id)) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败!");
    }
}
